package com.sangeng.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.constants.SystemConstants;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.entity.Article;
import com.sangeng.domain.entity.Category;
import com.sangeng.domain.vo.CategoryVo;
import com.sangeng.mapper.ArticleMapper;
import com.sangeng.mapper.CategoryMapper;
import com.sangeng.service.CategoryService;
import com.sangeng.utils.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

//    private final ArticleService articleService;
      private final ArticleMapper articleMapper;
    @Override
    public ResponseResult<List<CategoryVo>> getCategoryList() {
        //查询文章表
        LambdaQueryWrapper<Article> articleWrapper = new LambdaQueryWrapper<>();
        //判断是否正常发布状态
        articleWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articles = articleMapper.selectList(articleWrapper);
        //articleService.list(articleWrapper);

        //获取文章的分类id 并且去重(不同文章可能在同一个分类id下面）
        //为什么需要获取文章的分类id，因为用户会点击超链接进去分类页面的详情页下
        //当进入详情页的时候，我们需要展示该分类下的所有文章，怎么查？利用分类id在分类表中查，所以我们需要分类id
        //利用Strem流获取到id，然后把流对象封装为一个xxx数据结构返回，在这里用的是toSet，封装为集合返回。
        Set<Long> categoryIds = articles.stream()
                .map(Article::getCategoryId)
                .collect(Collectors.toSet());

        //查询分类表 要求分类状态是正常
        List<Category> categories = listByIds(categoryIds);

        categories = categories.stream().filter(category -> {//过滤文章是否为正常状态
            return SystemConstants.STATUS_NORMAL.equals(category.getStatus());
        }).collect(Collectors.toList());

        //封装vo
        List<CategoryVo> categoryVoList = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        return ResponseResult.okResult(categoryVoList);
    }

    @Override
    public ResponseResult<List<CategoryVo>> getAllCategoryList() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getStatus, SystemConstants.NORMAL);
        List<Category> list = list(wrapper);

        //封装vo
        List<CategoryVo> categoryVoList = BeanCopyUtils.copyBeanList(list, CategoryVo.class);
        return ResponseResult.okResult(categoryVoList);
    }
}
